package tuplestore

import (
	"errors"
	"sync"
	"time"

	"github.com/prometheus/client_golang/prometheus"
)

var (
	ErrDuplicateID  = errors.New("duplicate tuple ID")
	ErrNilTuple     = errors.New("nil tuple provided")
	ErrEmptyTupleID = errors.New("empty tuple ID")
	ErrStoreFull    = errors.New("tuple store is full")
	ErrNotFound     = errors.New("tuple not found")
)

type Metrics struct {
	InsertCount    prometheus.Counter
	InsertDuration prometheus.Histogram
	MergeCount     prometheus.Counter
	MergeDuration  prometheus.Histogram
	SegmentCount   prometheus.Gauge
	BlockCount     prometheus.Gauge
	DeltaStoreSize prometheus.Gauge
	MainStoreSize  prometheus.Gauge
}

// ElementType 定义元组中元素的类型
type ElementType int

const (
	TypeInt32 ElementType = iota
	TypeInt64
	TypeFloat32
	TypeFloat64
	TypeString
	TypeBool
	TypeTime
)

// ElementInfo 描述元组中元素的信息
type ElementInfo struct {
	Type     ElementType
	Offset   int
	Size     int
	Nullable bool
}

// Tuple 数据元组
type Tuple struct {
	ID        string
	Data      []byte
	Timestamp time.Time
	Schema    []ElementInfo // 描述元组数据的格式
}

type Config struct {
	MergeThreshold   int
	MaxDeltaSize     int64
	MaxMergeInterval time.Duration
	InitialSegments  int
	BlocksPerSegment int
	UseCompression   bool // 是否启用压缩存储
}

type TupleStore struct {
	mu               sync.RWMutex
	segments         map[string]*Segment
	idIndex          *Index
	mergeThreshold   int
	maxDeltaSize     int64
	maxMergeInterval time.Duration
	metrics          Metrics
	useCompression   bool

	idRangeSegments []*Segment
	timeSegments    []*Segment
}

type Segment struct {
	ID      string
	Blocks  map[string]*Block
	mu      sync.RWMutex
	created time.Time
}

type Block struct {
	ID                string
	DeltaStore        *DeltaStore
	MainStore         *MainStore
	LastMergeTime     time.Time
	mu                sync.RWMutex
	Schema            []ElementInfo             // 添加 Schema 字段
	CompressedColumns map[int]*CompressedColumn // 添加压缩列存储
	useCompression    bool
}

type DeltaStore struct {
	mu     sync.RWMutex
	tuples map[string]*Tuple
	// 新增的元组
	AddedTuples []*Tuple
	// 更新的元组 (ID -> 新元组)
	UpdatedTuples map[string]*Tuple
	// 已删除的元组 ID 集合
	DeletedIDs map[string]struct{}
	// 变更计数，用于决定何时触发合并
	ChangeCount int
	size        int64
}

type MainStore struct {
	mu     sync.RWMutex
	tuples map[string]*Tuple
}

// Condition 定义查询条件
type Condition struct {
	ElementIndex int         // 元组中元素的索引
	Operator     string      // 操作符：=, >, <, >=, <=, !=
	Value        interface{} // 比较值
}

// BlockRef 表示块的引用
type BlockRef struct {
	SegmentID string
	BlockID   string
}

// IndexPlan 表示查询计划
type IndexPlan struct {
	IndexType  string      // 索引类型：primary, secondary, etc.
	KeyColumns []int       // 用于索引的列
	Filter     []Condition // 过滤条件
	SortOrder  []int       // 排序顺序
	Limit      int         // 结果限制
	Offset     int         // 偏移量
}
